package com.sopt.friends.sub;

import java.io.InputStream;
import java.util.ArrayList;

import com.sopt.friends.R;
import com.sopt.friends.db.FriendsDBHelper;
import com.sopt.friends.db.Constants.FriendsDB;
import com.sopt.friends.vo.FriendsBasicMember;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;

import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class SubMemberInfo extends Activity implements OnItemSelectedListener{
	TextView nameView;
	TextView twitterView;
	TextView me2dayView;
	TextView facebookView;
	
	Spinner groupSpinner;
	Spinner monthSpinner;
	Spinner daySpinner;
	
	String curMemberSeq = "";
	
	int curDayPosition = 0;
	int curMonthPosition = 0;
	int curGroupPosition = 0;
	String curGroupSeq;
	Button btnSave;
	Button btnSaveBottom;
	FriendsBasicMember curMember;
	
	ArrayList<String> month = new ArrayList<String>();
	ArrayList<String> days = new ArrayList<String>();
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.memberinfo);
		curMemberSeq = getIntent().getAction();
		
		nameView = (TextView)findViewById(R.id.infoName);
		twitterView = (TextView)findViewById(R.id.infoTwitter);
		me2dayView = (TextView)findViewById(R.id.infoMe2day);
		facebookView = (TextView)findViewById(R.id.infoFacebook);
		
		btnSave = (Button)findViewById(R.id.infoSave);
		btnSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				saveMember();
			}
		});
		btnSaveBottom = (Button)findViewById(R.id.infoSaveBottom);
		btnSaveBottom.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				saveMember();
			}
		});
		
	}
	
	protected void saveMember() {
		FriendsDBHelper dbhelper = new FriendsDBHelper(this);
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		
		values.put(FriendsDB.MEMBER_BIRTHDAY, monthSpinner.getSelectedItem().toString() +"-"+daySpinner.getSelectedItem().toString() );
		values.put(FriendsDB.MEMBER_BIRTHDAY, monthSpinner.getSelectedItem().toString() +"-"+daySpinner.getSelectedItem().toString() );
		values.put(FriendsDB.MEMBER_NAME, nameView.getText().toString());
		
		values.put(FriendsDB.GROUP_SEQ, curGroupSeq);
		
		String where = FriendsDB.MEMBER_ID +" = "+ curMember.get_id();
		
		int res = db.update(FriendsDB.TABLE_MEMBER, values, where, null);
		
		where = FriendsDB.MEMBER_ID +"="+curMember.get_id(); 
		db.delete(FriendsDB.TABLE_SNS, where, null);
		
		ContentValues snsValues = new ContentValues();
		snsValues.put(FriendsDB.SNS_TWITTER, twitterView.getText().toString());
		snsValues.put(FriendsDB.SNS_ME2DAY, me2dayView.getText().toString());
		snsValues.put(FriendsDB.SNS_FACEBOOK, facebookView.getText().toString());
		snsValues.put(FriendsDB.MEMBER_ID, curMember.get_id());
		if(db.insert(FriendsDB.TABLE_SNS,null,snsValues)>0){
			res++;
		}
		db.close();
		
		if(res==2){
			showToast(getResources().getString(R.string.toastSaveComplete));
			finish();
		}else{
			showToast(getResources().getString(R.string.toastError));
		}
	}

	protected void onResume() {
		super.onResume();
		monthSpinner = (Spinner)findViewById(R.id.infoMonth);
		daySpinner = (Spinner)findViewById(R.id.infoDay);
		
		initBirthDaySpinner();
		
		groupSpinner = (Spinner)findViewById(R.id.infoGroupName);
		
		ArrayList<String>grouplist = getGroupList();
		
		curMemberSeq = getIntent().getAction();
		curMember = getMemberInfo(curMemberSeq);
		
		nameView.setText(curMember.getDisplayname());
		twitterView.setText(curMember.getTwitter());
		me2dayView.setText(curMember.getTwitter());
		facebookView.setText(curMember.getTwitter());
		
		daySpinner.setSelection(curDayPosition, true);
		monthSpinner.setSelection(curMonthPosition, true);
		
		curGroupPosition = 0;
		for(String cur:grouplist){
			if(cur.equals(curMember.getGroupname())){
				groupSpinner.setSelection(curGroupPosition);
				break;
			}
			curGroupPosition++;
		}
		
	}
	private void initBirthDaySpinner(){
		month = new ArrayList<String>();
		days = new ArrayList<String>();
		for(int i = 1;i<32;i++){
			String curValue = "";
			if(i<10)curValue = "0"+i;
			else curValue = String.valueOf(i);
			
			days.add(curValue);
			if(i<13)month.add(curValue);
		}
		
		ArrayAdapter<String> monthArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,month);
		
		monthSpinner.setAdapter(monthArrayAdapter);
		
		monthSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			public void onItemSelected(AdapterView<?> parent, View view, int position,
					long id) { monthSpinnerSet(position);
					}
			public void onNothingSelected(AdapterView<?> arg0) {}
		});
		
		ArrayAdapter<String> daysArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,days);
		
		daySpinner.setAdapter(daysArrayAdapter);
		
		daySpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			public void onItemSelected(AdapterView<?> parent, View view, int position,
					long id) { daySpinnerSet(position);
					}
			public void onNothingSelected(AdapterView<?> arg0) {}
		});
	}
	
	
	protected void daySpinnerSet(int position) {
		curDayPosition = position;
	}

	protected void monthSpinnerSet(int position) {
		curMonthPosition = position;
	}

	private ArrayList<String> getGroupList() {
		FriendsDBHelper dbhelper = new FriendsDBHelper(this);
		SQLiteDatabase db = dbhelper.getReadableDatabase();
		Cursor cursor =  db.query(FriendsDB.TABLE_GROUP, null, null, null, null, null, null);
		ArrayList<String>list = new ArrayList<String>();
		while(cursor.moveToNext()){
			String curGroupName = cursor.getString(cursor.getColumnIndex(FriendsDB.GROUP_NAME));
			list.add(curGroupName);
		}
		cursor.close();
		db.close();
		
		ArrayAdapter<String> groupArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
		
		groupSpinner.setAdapter(groupArrayAdapter);
		
		groupSpinner.setOnItemSelectedListener(this);
		return list;
	}
	
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		curGroupPosition = position;
		curGroupSeq = getGroupSeqByName(groupSpinner.getSelectedItem().toString());
	}

	public void onNothingSelected(AdapterView<?> parent) {}

	private FriendsBasicMember getMemberInfo(String curMem) {
		String contactId = "";
		String displayName = "";
		String groupseq = "";
		String birthday = "";
		String twitter = "";		
		String me2day = "";
		String facebook = "";
		Bitmap photo = null;
		
		FriendsDBHelper dbhelper = new FriendsDBHelper(this);
		SQLiteDatabase db = dbhelper.getReadableDatabase();
		String where = FriendsDB.MEMBER_ID+" = ('"+curMem+"')";
		Cursor cursor =  db.query(FriendsDB.TABLE_MEMBER, null, where, null, null, null, null);
		
		FriendsBasicMember mem = new FriendsBasicMember();
		if(cursor.moveToNext()){
			contactId  = cursor.getString(cursor.getColumnIndex(FriendsDB.MEMBER_ID));
			displayName  = cursor.getString(cursor.getColumnIndex(FriendsDB.MEMBER_NAME));
			groupseq  = cursor.getString(cursor.getColumnIndex(FriendsDB.GROUP_SEQ));
			curGroupSeq = groupseq;
			birthday  = cursor.getString(cursor.getColumnIndex(FriendsDB.MEMBER_BIRTHDAY));
			
			if(birthday!=null && birthday.length()>3){
				String[] birth = birthday.split("-");
				curDayPosition = Integer.parseInt(birth[1])-1;
				curMonthPosition = Integer.parseInt(birth[0])-1;
				
			}

			mem.set_id(contactId);
			mem.setDisplayname(displayName);
			mem.setGroupseq(groupseq);
			mem.setBirthday(birthday);
			
			Uri uri = ContentUris.withAppendedId(
					ContactsContract.Contacts.CONTENT_URI, Long
							.parseLong(contactId));
			
			InputStream is = ContactsContract.Contacts
					.openContactPhotoInputStream(getContentResolver(), uri);

			photo = BitmapFactory.decodeStream(is);
			
			mem.setPhoto(photo);
		}
		cursor.close();
		
		where = FriendsDB.MEMBER_ID +" = "+ curMemberSeq;
		cursor =  db.query(FriendsDB.TABLE_SNS, null, where, null, null, null, null);
		
		if(cursor.moveToNext()){
			twitter = cursor.getString(cursor.getColumnIndex(FriendsDB.SNS_TWITTER));
			me2day = cursor.getString(cursor.getColumnIndex(FriendsDB.SNS_ME2DAY));
			facebook = cursor.getString(cursor.getColumnIndex(FriendsDB.SNS_FACEBOOK));
			
			mem.setTwitter(twitter);
			mem.setMe2day(me2day);
			mem.setFacebook(facebook);
		}
		cursor.close();
		
		where = FriendsDB.GROUP_SEQ + " = "+mem.getGroupseq();
		cursor =  db.query(FriendsDB.TABLE_GROUP, null, where, null, null, null, null);
		
		if(cursor.moveToNext()){
			mem.setGroupname(cursor.getString(cursor.getColumnIndex(FriendsDB.GROUP_NAME)));
		}
		cursor.close();
		
		db.close();
		
		return mem;
		
	}
	
	private String getGroupSeqByName(String name){
		String result = "";
		FriendsDBHelper dbhelper = new FriendsDBHelper(this);
		SQLiteDatabase db = dbhelper.getReadableDatabase();
		String[]column = {FriendsDB.GROUP_SEQ};
		String where = FriendsDB.GROUP_NAME+" = ('"+name+"')";
		Cursor cursor =  db.query(FriendsDB.TABLE_GROUP, column, where, null, null, null, null);
		if(cursor.moveToNext()){
			result = cursor.getString(cursor.getColumnIndex(FriendsDB.GROUP_SEQ));
		}
		cursor.close();
		return result;
	}

	private void showToast(String msg){
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}
	private void showToastLong(String msg){
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}

}
